<?php

namespace catchAdmin\apidoctor\controller;

use app\common\lib\Redis;
use app\common\lib\ZhyxMongo;
use app\common\model\BaseModel;
use app\common\model\CircleComments;
use app\common\model\WardmateCircle;
use app\common\model\WardmateCircleContent;
use app\Request;
use catcher\CatchResponse;
use catcher\base\CatchRequest;
use catcher\base\CatchController;
use app\common\model\WardmateCircle as WcircleModel;
use catchAdmin\apidoctor\validate\CircleValidate;
use catcher\exceptions\FailedException;
use MongoDB\BSON\ObjectId;
use think\exception\ValidateException;
use catchAdmin\apidoctor\service\CircleService;
use app\common\business\Circle as BusinessCircle;

class Circle extends CatchController
{
    protected $wcircle;

    public function __construct(WcircleModel $wcircle)
    {
        $this->wcircle = $wcircle;
    }

    /**
     * 创建群聊
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function establish(CatchRequest $request): \think\response\Json
    {
        $req = $request->param();
        $req['doctor_code'] = request()->userInfo['doctor_code'];

        try {
            validate(CircleValidate::class)->scene('establish')->check($req);
        } catch (ValidateException $e) {
            return CatchResponse::fail($e->getError());
        }
        return CatchResponse::success($this->wcircle->addData($req));
    }

    /**
     * 获取群聊列表
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function group_chat_list(Request $request): \think\response\Json
    {
        $req = $request->param();
        $map = [];
        $platform = $request->userInfo["platform"] ?? "1";
        if ($platform === "1") {
            $req['doctor_code'] = request()->userInfo['doctor_code'];
            try {
                validate(CircleValidate::class)->scene('group_chat_list')->check($req);
            } catch (ValidateException $e) {
                return CatchResponse::fail($e->getError());
            }

            $map[] = ['doctor_code', '=', $req['doctor_code']];
        } else {
            $map[] = ['patientList.patientId', '=', $request->userInfo["patientId"]];
        }


        $result = $this->wcircle->getLists($map, "id,title,created_at");

        return CatchResponse::paginate($result);
    }


    /**
     * 获取群聊基本信息
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function group_chat_info(Request $request): \think\response\Json
    {
        $req = $request->param();

        try {
            validate(CircleValidate::class)->scene('group_chat_info')->check($req);
        } catch (ValidateException $e) {
            return CatchResponse::fail($e->getError());
        }
        return CatchResponse::success((new CircleService())->getGroupChatInfo($req['id']));
    }

    /**
     * 修改群聊基本信息
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function modify_group_chat_info(CatchRequest $request): \think\response\Json
    {
        $req = $request->param();

        try {
            validate(CircleValidate::class)->scene('modify_group_chat_info')->check($req);
        } catch (ValidateException $e) {
            return CatchResponse::fail($e->getError());
        }
        return CatchResponse::success($this->wcircle->saveData($req['id'], $req));
    }

    /**
     * 获取成员列表
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function part_list(CatchRequest $request): \think\response\Json
    {
        $req = $request->param();
        $req['doctor_code'] = request()->userInfo['doctor_code'];

        try {
            validate(CircleValidate::class)->scene('part_list')->check($req);
        } catch (ValidateException $e) {
            return CatchResponse::fail($e->getError());
        }
        return CatchResponse::success((new CircleService())->getParts($req['id'], $req['doctor_code']));
    }

    /**
     * 加入群聊成员
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function add_group_chat_patient(CatchRequest $request): \think\response\Json
    {
        $req = $request->param();

        try {
            validate(CircleValidate::class)->scene('add_group_chat_patient')->check($req);
        } catch (ValidateException $e) {
            return CatchResponse::fail($e->getError());
        }
        return CatchResponse::success((new CircleService())->addGroupChat($req['id'], $req['patientList']));
    }

    /**
     * 解散群聊
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function dissolution(CatchRequest $request): \think\response\Json
    {
        $req = $request->param();
        $req['doctor_code'] = request()->userInfo['doctor_code'];

        try {
            validate(CircleValidate::class)->scene('dissolution')->check($req);
        } catch (ValidateException $e) {
            return CatchResponse::fail($e->getError());
        }
        return CatchResponse::success((new CircleService())->delGroupChat($req['id'], $req['doctor_code']));
    }

    /**
     * 获取群聊头部信息
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function group_chat_head(Request $request): \think\response\Json
    {
        $req = $request->param();

        try {
            validate(CircleValidate::class)->scene('group_chat_head')->check($req);
        } catch (ValidateException $e) {
            return CatchResponse::fail($e->getError());
        }
        return CatchResponse::success((new BusinessCircle())->getHeadinfo($req['id']));
    }

    /**
     * 上传朋友圈素材
     * @param CatchRequest $request
     */
    public function uploadMaterial(Request $request): \think\response\Json
    {
        $business = new BusinessCircle();
        $files = $request->file('files');
        $postData = $request->param();
        try {
            //执行图片上传操作
            $uploadResult = $business->uploadFiles($files);
            return CatchResponse::success($uploadResult);

        } catch (ValidateException $e) {
            return CatchResponse::fail($e->getError());
        }
    }

    public function comment(Request $request): \think\response\Json
    {
        $postData = $request->param();
        $platform = (string)$request->userInfo["platform"];
        try {

            validate(CircleValidate::class)->scene("comment")->check($postData);
            //判断父类id是否为空
            $circleInfo = (new WardmateCircleContent())->find($postData["circle_id"]);
            if (empty($circleInfo)) {
                throw new FailedException("朋友圈内容不存在");
            }
            if (isset($postData["parentId"]) && !empty($postData["parentId"])) {
                $replayUserInfo = (new CircleComments())->find(new ObjectId($postData["parentId"]));
            }
            $data = [
                'circle_id' => $postData["circle_id"],
                'uid' => $platform === "1" ? $request->userInfo["id"] : $request->userInfo["patientId"],
                'name' => $platform === "1" ? $request->userInfo["username"] : $request->userInfo["name"],
                'platform' => $platform,
                'parentId' => $postData["parentId"] ?? "",
                'replay_user' => $replayUserInfo["name"] ?? "",
                'replay_uid' => $replayUserInfo["uid"] ?? 0,
                'deleted_at' => 0,
                'content' => $postData['content'],
            ];
            //追加可删除的人员id
            $data["opt_users"] = [$data["uid"], $circleInfo["uid"]];
            $data["type"] = empty($data["parentId"]) ? 1 : 2;
            //执行数据的写入操作
            $result = (new CircleComments())->createBy($data);
            if (!empty($result)) {
                //未读消息增加计数
                $uid = $data["replay_uid"] ?: $circleInfo["uid"];
                Redis::getInstance()->redis->hincrby("circle:unread", $uid, 1);
                Redis::getInstance()->redis->lpush("circle:unread:{$uid}", $result);
                ZhyxMongo::getInstance()->setCollection('wardmate_circle_content')->updateOne(["_id" => new ObjectId($circleInfo["id"])], ['$inc' => ["comment_count" => 1]]);
            }
            return CatchResponse::success("发布成功");
        } catch (ValidateException $validateException) {
            return CatchResponse::fail($validateException->getError());
        }
    }

    public function release(Request $request): \think\response\Json
    {
        $business = new BusinessCircle();
        $postData = $request->param();
        try {
            validate(CircleValidate::class)->scene("release")->check($postData);
            $platform = (string)$request->userInfo["platform"];
            $data = [
                "group_id" => $postData["group_id"],
                "written" => $postData["title"],
                "midia_list" => $postData["media_list"] ?? [],
                "type" => $postData["type"],
                "uid" => $platform == "1" ? (int)$request->userInfo["id"] : (int)$request->userInfo["patientId"],
                'name' => $platform == "1" ? $request->userInfo["username"] : $request->userInfo["name"],
                'userType' => $platform,
                'comment_count' => 0,
                'deleted_at' => 0,
                'visible_mode' => $postData["visible_mode"] ? (int)$postData["visible_mode"] : 1
            ];
            $result = $business->release($data);
            return CatchResponse::success(["release_id" => $result]);
        } catch (ValidateException $e) {
            return CatchResponse::fail($e->getError());
        }
    }

    public function getReleaseList(Request $request): \think\response\Json
    {

        $groupId = $request->param("group_id", "", "string");
        if (empty($groupId)) {
            throw new FailedException("分组id必须填写");
        }
        $groupInfo = (new WardmateCircle())->findBy($groupId);
        if (empty($groupInfo)) {
            throw new FailedException("群聊不存在");
        }
        $uid = $request->param("uid", "", "int");

        //根据分布id获取数据
        $result = (new WardmateCircleContent())->getListByGroupId($groupId, $uid);
        if (count($result->items()) > 0) {
            $result->append(["comment", "can_delete"]);
        }
        return CatchResponse::paginate($result);
    }

    public function getReleaseDetail(Request $request, string $contentId): \think\response\Json
    {
        //根据分布id获取数据
        $result = (new WardmateCircleContent())->getContentById($contentId);
        if (!empty($result)) {
            $result->append(["comment", "can_delete"]);
        }
        return CatchResponse::success($result);
    }

    public function deleteArticle(Request $request, string $id): \think\response\Json
    {
        $result = (new WardmateCircleContent())->getContentById($id);
        if (empty($result)) {
            throw new FailedException("朋友圈内容不存在");
        }
        $patientId = request()->userInfo["platform"] === "1" ? (int)request()->userInfo["id"] : (int)request()->userInfo["patientId"];
        //判断发布者是否是登录人
        if ($result["uid"] !== $patientId) {
            throw new FailedException("您不是创建人，不能删除该朋友圈");
        }
        return CatchResponse::success((new WardmateCircleContent())->deleteBy($id));

    }


    /**
     * 获取加入群聊的成员列表
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function joined_members(Request $request): \think\response\Json
    {
        $req = $request->param();
        try {
            validate(CircleValidate::class)->scene('joined_members')->check($req);
        } catch (ValidateException $e) {
            return CatchResponse::fail($e->getError());
        }
        return CatchResponse::success((new CircleService())->getJoinedMembers($req['id']));
    }

    /**
     * 移除群聊的成员
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function remove_members(Request $request): \think\response\Json
    {
        $req = $request->param();

        $req['doctor_code'] = request()->userInfo['doctor_code'];
        try {
            validate(CircleValidate::class)->scene('remove_members')->check($req);
        } catch (ValidateException $e) {
            return CatchResponse::fail($e->getError());
        }
        return CatchResponse::success((new CircleService())->removeMembers($req['id'], $req['doctor_code'], $req['patientId']));
    }

    public function getUnReadCount(Request $request): \think\response\Json
    {
        $platform = (string)$request->userInfo["platform"];
        $uid = $platform === "1" ? $request->userInfo["id"] : $request->userInfo["patientId"];
        $count = 0;
        if (Redis::getInstance()->redis->hexists("circle:unread", $uid)) {
            $count = Redis::getInstance()->redis->hget("circle:unread", $uid);
        }
        return CatchResponse::success(["count" => $count]);
    }

    public function getUnReadList(Request $request): \think\response\Json
    {
        $platform = (string)$request->userInfo["platform"];
        $uid = $platform === "1" ? $request->userInfo["id"] : $request->userInfo["patientId"];
        $result = [];
        $redisUnReadCountKey = "circle:unread";
        $redisUnReadKey = "circle:unread:" . $uid;
        if (Redis::getInstance()->redis->exists($redisUnReadKey)) {
            $commentIds = Redis::getInstance()->redis->lrange($redisUnReadKey, 0, -1);
            $result = (new CircleComments())->where("id", "in", $commentIds)->order("_id", "desc")->select();
        }
        Redis::getInstance()->redis->hset($redisUnReadCountKey, $uid, 0);
        Redis::getInstance()->redis->del($redisUnReadKey);
        return CatchResponse::success($result);
    }

    public function delComment(Request $request, string $id): \think\response\Json
    {
        $commentInfo = (new CircleComments())->find($id);
        if (empty($commentInfo)) {
            throw new FailedException("评论不存在");
        }
        $loginUserId = request()->userInfo["platform"] === "1" ? request()->userInfo["id"] : request()->userInfo["patientId"];
        if (in_array($loginUserId, $commentInfo["opt_users"], true)) {
            return CatchResponse::success((new CircleComments())->deleteBy($id));
        }
        throw new FailedException("您不是该内容的发布者或不是该条评论的创建者，不能进行删除操作");
    }


}